package com.yimixian.app.location;

import com.baidu.location.BDLocation;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.Marker;
import com.baidu.mapapi.map.offline.MKOLSearchRecord;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.search.core.PoiInfo;
import com.baidu.mapapi.search.poi.OnGetPoiSearchResultListener;
import com.baidu.mapapi.search.poi.PoiCitySearchOption;
import com.baidu.mapapi.search.poi.PoiDetailResult;
import com.baidu.mapapi.search.poi.PoiResult;
import com.baidu.mapapi.search.poi.PoiSearch;
import com.facebook.rebound.Spring;
import com.facebook.rebound.SpringConfig;
import com.facebook.rebound.SpringListener;
import com.ta.utdid2.android.utils.StringUtils;
import com.yimixian.app.R;
import com.yimixian.app.YMXApplication;
import com.yimixian.app.activity.BaseNaviFragmentGroupActivity;
import com.yimixian.app.adapter.AroundPoiAdapter;
import com.yimixian.app.adapter.PoiListViewAdapter;
import com.yimixian.app.address.BaiduMapUtilByRacer;
import com.yimixian.app.address.LocationBean;
import com.yimixian.app.address.MutableAddress;
import com.yimixian.app.common.SpringCreator;
import com.yimixian.app.data.DataManager;
import com.yimixian.app.ui.AroundPoiLinearlayout;
import com.yimixian.app.util.Strings;
import com.yimixian.app.util.UiUtils;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.List;

import butterknife.ButterKnife;
import butterknife.InjectView;

public class CheckAddressInfoMapActivity extends BaseNaviFragmentGroupActivity implements
        AdapterView.OnItemClickListener, AroundPoiLinearlayout.ShowAnimationStatus {

    private static final SpringConfig SPRING_CONFIG = SpringConfig.fromOrigamiTensionAndFriction(
            20, 10);
    public static final String EXTRA_MUTABLE_ADDRESS = "extra_mutable_address";

    @InjectView(R.id.top)
    FrameLayout top;
    @InjectView(R.id.location_icon)
    ImageView mLocationIcon;
    @InjectView(R.id.map_view)
    MapView mMapView;
    @InjectView(R.id.bottom_lin)
    AroundPoiLinearlayout bottomLin;
    @InjectView(R.id.list_view)
    ListView mGeoSearchList;
    @InjectView(R.id.tvShowLocation)
    TextView tvShowLocation;
    @InjectView(R.id.poi_search_edit_text)
    EditText mPoiSearchEditText;
    @InjectView(R.id.poi_list_view)
    ListView mPoiListView;
    @InjectView(R.id.list_progress_bar)
    View mListProgressBar;
    @InjectView(R.id.current_location)
    ImageView currentLocation;
    @InjectView(R.id.rel_search)
    RelativeLayout relSearch;
    @InjectView(R.id.title_bar_left_btn)
    ImageButton backBtn;


    private PoiSearch mPoiSearch;
    private ArrayList<PoiInfo> mPoiInfoList;
    private PoiListViewAdapter mPoiListViewAdapter;

    private int topDistance = 150;
    private int animationTime = 200;
//    boolean isCanUpdateMap;
    private DataManager mDataManager;
    private BaiduMap mBaiduMap;
    private Spring mSpring;
    private MutableAddress mMutableAddress;
    private AroundPoiAdapter mAroundPoiAdapter;
    private List<PoiInfo> mAroundPoiList = new ArrayList<>();
    private Marker mMarker;
    private String currentCity = "";
    private int selectPoiIndex = -1;
    MyGeoCodePoiListener myGeoCodePoiListener;
    private PoiInfo currentSearchPoiInfo;
    private boolean isSearchClick;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        mDataManager = DataManager.getInstance();
        mSpring = SpringCreator.create();
        setContentView(R.layout.map_activity);
        ButterKnife.inject(this);
        initBaiduMapView();
        backBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        currentLocation.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                LocationProvider.getInstance().startBaiduLocated(false, new LocatedListener() {

                    @Override
                    public void locatedSuccessListener(BDLocation location) {
                        BaiduMapUtilByRacer.moveToTarget(
                                location.getLatitude(),
                                location.getLongitude(), mBaiduMap);
                    }

                    @Override
                    public void locatedSuccessGeoPoiInfoListener(PoiInfo poiInfo) {

                    }

                    @Override
                    public void locatedFailedListener() {
                        UiUtils.showToast("定位失败");
                    }

                    @Override
                    public void locatedFailedGeoPoiInfoListener() {

                    }
                });
            }
        });
        mMutableAddress = getIntent()
                .getParcelableExtra(CheckAddressInfoMapActivity.EXTRA_MUTABLE_ADDRESS);
        myGeoCodePoiListener = new MyGeoCodePoiListener();
        bottomLin.setShowAnimationStatus(this);
        mAroundPoiAdapter = new AroundPoiAdapter(this, mAroundPoiList, mMutableAddress);
        mGeoSearchList.setAdapter(mAroundPoiAdapter);
        mGeoSearchList.setOnItemClickListener(this);
        if (mMutableAddress == null || StringUtils.isEmpty(mMutableAddress.city)) {
            finish();
            return;
        }
        mPoiSearchEditText.setText("");
        relSearch.setVisibility(View.GONE);
        currentCity = mMutableAddress.city;
        if (!StringUtils.isEmpty(mMutableAddress.latitude) &&
                !StringUtils.isEmpty(mMutableAddress.longitude)) {
            LatLng latLng = new LatLng(Double.valueOf(mMutableAddress.latitude),
                    Double.valueOf(mMutableAddress.longitude));
            setBaiduMapLatLng(latLng);
        }else{//肯定是新建地址 并且前面页面没有定位到
            // TODO: 2015/11/23 定位当前位置  loading
            //判断是不是当前城市  不是 定位城市中心  是定位当前位置
            LocationProvider.getInstance().startBaiduLocated(false, new LocatedListener() {

                @Override
                public void locatedSuccessListener(BDLocation location) {
                    if (currentCity != null){
                        String cityName = currentCity;
                        if (!currentCity.contains("市")) cityName = currentCity + "市";
                        if (location.getCity().equals(currentCity) ||
                                location.getCity().equals(cityName)){//是当前城市
                            setBaiduMapLatLng(new LatLng(location.getLatitude(), location.getLongitude()));
                        }else{//不是当前城市  定位中心位置
                            loacatedCenter();
                        }
                    }else {//不是当前城市  定位中心位置
                        loacatedCenter();
                    }
                }

                @Override
                public void locatedSuccessGeoPoiInfoListener(PoiInfo poiInfo) {

                }

                @Override
                public void locatedFailedListener() {
                    loacatedCenter();
                }

                @Override
                public void locatedFailedGeoPoiInfoListener() {

                }
            });

        }

        mPoiSearch = PoiSearch.newInstance();
        //获取检索内容监听
        mPoiSearch.setOnGetPoiSearchResultListener(new OnGetPoiSearchResultListener() {
            @Override
            public void onGetPoiResult(PoiResult poiResult) {
                mListProgressBar.setVisibility(View.INVISIBLE);
                if (poiResult == null || poiResult.getAllPoi() == null) {
                    mPoiInfoList = null;
                } else {
                    mPoiInfoList = new ArrayList<>();
                    for (PoiInfo poiInfo : poiResult.getAllPoi()) {
                        if (!poiInfo.address.contains(";")) {
                            mPoiInfoList.add(poiInfo);
                        }
                    }
                }
                mPoiListViewAdapter.setList(mPoiInfoList);
                mPoiListViewAdapter.notifyDataSetChanged();
            }

            @Override
            public void onGetPoiDetailResult(PoiDetailResult poiDetailResult) {

            }
        });

        //编辑框输入状态监听
        mPoiSearchEditText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                String str = s.toString();
                if (Strings.isNullOrEmpty(str)) {
                    mPoiInfoList = null;
                    mPoiListViewAdapter.setList(mPoiInfoList);
                    mPoiListViewAdapter.notifyDataSetChanged();
                    mListProgressBar.setVisibility(View.INVISIBLE);
                    relSearch.setVisibility(View.GONE);
                    return;
                }
                relSearch.setVisibility(View.VISIBLE);
                mPoiSearch.searchInCity(new PoiCitySearchOption()
                        .city(currentCity)
                        .keyword(str)
                        .pageCapacity(20));
                mListProgressBar.setVisibility(View.VISIBLE);
            }
            @Override
            public void afterTextChanged(Editable s) {

            }
        });

        mPoiListViewAdapter = new PoiListViewAdapter(this);
        mPoiListViewAdapter.setList(mPoiInfoList);
        mPoiListView.setAdapter(mPoiListViewAdapter);
        mPoiListView.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {
                if (scrollState == SCROLL_STATE_TOUCH_SCROLL) {
                    InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                    imm.hideSoftInputFromWindow(mPoiSearchEditText.getWindowToken(), 0);
                }
            }
            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount,
                                 int totalItemCount) {
            }
        });

        mPoiListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                PoiInfo poiInfo = mPoiListViewAdapter.mList.get(position);
//                mMutableAddress.poiId = "bd-" + poiInfo.uid;
//                mMutableAddress.poiName = poiInfo.name;
//                mMutableAddress.poiAddress = poiInfo.address;
                if (poiInfo.location == null) {
                    UiUtils.showToast("poi信息为空");
                    return;
                }
                if (mMutableAddress == null) mMutableAddress = new MutableAddress();
                mMutableAddress.poiName = poiInfo.name;
                mMutableAddress.city = currentCity;
                mMutableAddress.poiId = poiInfo.uid;
                mMutableAddress.latitude = String.valueOf(poiInfo.location.latitude);
                mMutableAddress.longitude = String.valueOf(poiInfo.location.longitude);
                mMutableAddress.address = poiInfo.address;
                mMutableAddress.poiAddress = poiInfo.address;
                setResult(RESULT_OK, new Intent().putExtra(EXTRA_MUTABLE_ADDRESS, mMutableAddress));
                finish();


//                if (mBaiduMap == null) setBaiduMapLatLng(poiInfo.location);
//                else BaiduMapUtilByRacer.moveToTarget(
//                        poiInfo.location.latitude,
//                        poiInfo.location.longitude, mBaiduMap);
//                currentSearchPoiInfo = poiInfo;
//                isSearchClick = true;
//                mPoiSearchEditText.setText(poiInfo.name);
//                if (!StringUtils.isEmpty(poiInfo.name))
//                    mPoiSearchEditText.setSelection(poiInfo.name.length());
////                mPoiInfoList = null;
////                mPoiListViewAdapter.setList(mPoiInfoList);
////                mPoiListViewAdapter.notifyDataSetChanged();
//                mListProgressBar.setVisibility(View.INVISIBLE);
//                relSearch.setVisibility(View.GONE);
//                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
//                imm.hideSoftInputFromWindow(mPoiSearchEditText.getWindowToken(), 0);
            }
        });
//        isCanUpdateMap = true;
    }

    public void initBaiduMapView(){
        mMapView.showZoomControls(false); // 隐藏比例尺控件
        mMapView.showScaleControl(true); // 隐藏缩放按钮
        mBaiduMap = mMapView.getMap();
        mBaiduMap.setMapType(BaiduMap.MAP_TYPE_NORMAL);
        MapStatusUpdate mapStatusUpdate = MapStatusUpdateFactory.zoomTo(19.0f);// 缩放级别[3, 20]
        mBaiduMap.setMapStatus(mapStatusUpdate);
        mBaiduMap.getUiSettings().setOverlookingGesturesEnabled(false);
        mBaiduMap.getUiSettings().setRotateGesturesEnabled(false);
        mBaiduMap.getUiSettings().setCompassEnabled(false);
        mBaiduMap.setOnMapStatusChangeListener(new BaiduMap.OnMapStatusChangeListener() {
            @Override
            public void onMapStatusChangeStart(MapStatus mapStatus) {
                mSpring.setCurrentValue(0, true);
            }
            @Override
            public void onMapStatusChange(MapStatus mapStatus) {
            }
            @Override
            public void onMapStatusChangeFinish(MapStatus mapStatus) {
                mSpring.setEndValue(10);
                //移到别的城市不检索信息
                //                if (isCanUpdateMap){
                if (isSearchClick){
                    isSearchClick = false;
                }else{
                    currentSearchPoiInfo = null;
                }
                bottomLin.setDownAnimation();
                LatLng chosenLatlng = mapStatus.bound.getCenter();
                mMutableAddress.latitude = chosenLatlng.latitude + "";
                mMutableAddress.longitude = chosenLatlng.longitude + "";
                // 反Geo搜索
                reverseGeoCode(chosenLatlng);
                //                }else{
                //                    isCanUpdateMap = true;
                //                }
            }
        });
        mSpring.setSpringConfig(SPRING_CONFIG)
                .setOvershootClampingEnabled(true)
                .setCurrentValue(0)
                .setAtRest().addListener(new SpringListener() {
            @Override
            public void onSpringUpdate(Spring spring) {
                double value = spring.getCurrentValue();
                float animationRange = -1
                        * getResources().getDimension(R.dimen.map_animation_range);
                mLocationIcon.setTranslationY((float) (value > 4 ? (1 - (value - 4) / 6)
                        * animationRange :
                        value / 4 * animationRange));
            }

            @Override
            public void onSpringAtRest(Spring spring) {
                if (spring.getCurrentValue() == 10) {
                    mSpring.setCurrentValue(0, true);
                }
            }

            @Override
            public void onSpringActivate(Spring spring) {

            }

            @Override
            public void onSpringEndStateChange(Spring spring) {

            }
        });
    }

    public void setBaiduMapLatLng(LatLng latLng){
        if (mMapView == null || latLng == null) return;
        if (mBaiduMap == null){
            mBaiduMap = mMapView.getMap();
        }
        mBaiduMap.setMapStatus(MapStatusUpdateFactory.newLatLng(latLng));
        reverseGeoCode(latLng);
    }

    /**
     * 通过城市名称 获取兴趣点
     */
    public void loacatedCenter(){
        LocationBean locationBean = new LocationBean();
        locationBean.city = currentCity;
        locationBean.locName = currentCity;
        BaiduMapUtilByRacer.getLocationByGeoCode(locationBean, null, myGeoCodePoiListener);
    }
    /**
     * 通过经纬度 获取兴趣点
     * @param ll
     */
    public void reverseGeoCode(LatLng ll) {
        BaiduMapUtilByRacer.getPoisByGeoCode(ll.latitude, ll.longitude,
                myGeoCodePoiListener);
    }

    class MyGeoCodePoiListener implements BaiduMapUtilByRacer.GeoCodePoiListener {
        @Override
        public void onGetSucceed(LocationBean locationBean,
                                 List<PoiInfo> poiList) {
            LocationBean mLocationBean = (LocationBean) locationBean.clone();
            if (currentCity == null ||currentCity.length() <= 0) return;
            String cityName = currentCity;
            if (!currentCity.contains("市")) cityName = cityName + "市";

            if (!currentCity.equals(mLocationBean.city) &&
                    !cityName.equals(mLocationBean.city)){//不是当前城市 不检索
                if (mAroundPoiList == null) {
                    mAroundPoiList = new ArrayList<>();
                }else{
                    mAroundPoiList.clear();
                }
                PoiInfo poiInfo = new PoiInfo();
                poiInfo.address = getResources().getString(R.string.map_no_located_text);
                mAroundPoiList.add(poiInfo);
                mAroundPoiAdapter.setNewList(mAroundPoiList, -2);
                return;
            }
            setBaiduMapLatLng(new LatLng(locationBean.getLatitude(),
                    locationBean.getLongitude()));
            tvShowLocation.setText(mLocationBean.getCity() + "-"
                    + mLocationBean.getDistrict() + "-"
                    + mLocationBean.getStreet() + "-"
                    + mLocationBean.getStreetNum());
            if (mAroundPoiList == null) {
                mAroundPoiList = new ArrayList<>();
            }
            mAroundPoiList.clear();
            if (poiList != null) {
                mAroundPoiList.addAll(poiList);
            } else {
                Toast.makeText(CheckAddressInfoMapActivity.this, "该周边没有热点",
                        Toast.LENGTH_SHORT).show();
            }
            mAroundPoiList = BaiduMapUtilByRacer.getSortPoiInfos(mAroundPoiList,
                    mMutableAddress, currentSearchPoiInfo);
            mAroundPoiAdapter.setNewList(mAroundPoiList, 0);
        }

        @Override
        public void onGetFailed() {
            Toast.makeText(CheckAddressInfoMapActivity.this, "抱歉，未能找到结果",
                    Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (mMapView != null) {
            mMapView.onResume();
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (mMapView != null) {
            mMapView.onPause();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        YMXApplication.getInstance().locatedListener = null;
        if (mMapView != null) {
            mMapView.onDestroy();
        }
    }

    //兴趣点点击事件
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//        isCanUpdateMap = false;
        if (mAroundPoiList == null || mAroundPoiList.size() <= position) return;
        selectPoiIndex = position;
        if (mMarker != null) {
            mMarker.remove();
        }
//        tvShowLocation.setText(mAroundPoiList.get(position).city + "-"
//                + mAroundPoiList.get(position).address + "-"
//                + mAroundPoiList.get(position).name);
//        mMarker = BaiduMapUtilByRacer.showMarkerByResource(
//                mAroundPoiList.get(position).location.latitude,
//                mAroundPoiList.get(position).location.longitude, R.drawable.point,
//                mBaiduMap, 0, true);
//        BaiduMapUtilByRacer.moveToTarget(
//                mAroundPoiList.get(position).location.latitude,
//                mAroundPoiList.get(position).location.longitude, mBaiduMap);
//        mAroundPoiAdapter.setNewList(mAroundPoiList, selectPoiIndex);
        PoiInfo poiInfo = mAroundPoiList.get(position);
        if (StringUtils.isEmpty(poiInfo.name)){
            return;
        }
        mMutableAddress.poiName = poiInfo.name;
        mMutableAddress.city = currentCity;
        mMutableAddress.poiId = poiInfo.uid;
        mMutableAddress.latitude = String.valueOf(poiInfo.location.latitude);
        mMutableAddress.longitude = String.valueOf(poiInfo.location.longitude);
        mMutableAddress.address = poiInfo.address;
        mMutableAddress.poiAddress = poiInfo.address;
        setResult(RESULT_OK, new Intent().putExtra(EXTRA_MUTABLE_ADDRESS, mMutableAddress));
        finish();
    }

    @Override
    public void isShowAnimation(boolean isUp) {
//        if (isUp){
//            upAnimatin();
//        }else{
//            downAnimation();
//        }
    }

//    /**
//     * 动画上移动
//     */
//    public void upAnimatin(){
//        animatorUtils.translateY(top, 0, -topDistance, animationTime, null).start();
//        animatorUtils.translateY(bottomLin, 0, - 2 * topDistance, animationTime, null).start();
//        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
//                LinearLayout.LayoutParams.MATCH_PARENT, bottomLin.getHeight() + 2 * topDistance);
//        bottomLin.setLayoutParams(params);
//    }
//
//    /**
//     * 动画下移动
//     */
//    public void downAnimation(){
//        mGeoSearchList.setSelection(0);
//        animatorUtils.translateY(top, -topDistance, 0, animationTime, null).start();
//        ObjectAnimator objectAnimator = animatorUtils.translateY(
//                bottomLin, - 2 * topDistance, 0, animationTime, null);
//        objectAnimator.addListener(new Animator.AnimatorListener() {
//            @Override
//            public void onAnimationStart(Animator animation) {
//            }
//            @Override
//            public void onAnimationEnd(Animator animation) {
//                LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
//                        LinearLayout.LayoutParams.MATCH_PARENT,
//                        bottomLin.getHeight() - 2 * topDistance);
//                bottomLin.setLayoutParams(params);
//            }
//            @Override
//            public void onAnimationCancel(Animator animation) {
//            }
//            @Override
//            public void onAnimationRepeat(Animator animation) {
//            }
//        });
//        objectAnimator.start();
//    }
}
